import React,{useState} from 'react'
import { Icon } from 'antd-mobile'

import { BASEURL,reqHouseImgUpload } from '../../../api'

export default function ImageWall(props) {
  const initLimit=12
  const {submitData, setSubmitData,limit}=props

  const [fileData, setFileData] = useState(()=>{
    if(submitData.houseImg==='')return []
    return submitData.houseImg.data.split('|').reduce((p,c,index)=>{
      p.push({id:'f'+index,url:c,status:'success'})
      return p
    },[])
  })

  const inputChange=el=>{
    const {files}=el.target
    if(files.length===0)return //未选择图片时不做操作
    let index=fileData.length
    let File={id:'f'+index,file:files[0],status:'uploading',url:'',uploadPromise:null}
    let uploadPromise=new Promise(async resolve=>{
      File.url=await new Promise(async resolve=>{
        const file=new FormData()
        file.append('file',files[0])
        let res=await reqHouseImgUpload(file,{'Content-Type':'multipart/form-data'})
        resolve(res.body[0])
      })
      File.status='success'
      setFileData([...fileData,File])
      setSubmitData({...submitData,houseImg:{...submitData['houseImg'],data:[...fileData,File].map(i=>i.url).join('|')}})
      if(fileData.length!==initLimit-1)document.querySelector('#uploader').reset()   //重置input
      resolve()
    })
    File.uploadPromise=uploadPromise  
  }

  const deletedImg=index=>{
    let arr=fileData
    arr.splice(index,1)
    setFileData([...arr])
    setSubmitData({...submitData,houseImg:{...submitData['houseImg'],data:[...arr].map(i=>i.url).join('|')}})
  }

  return (
    <div className='image-wall'>
      {
        fileData.length===0?null:fileData.map((f,index)=>(
        <div className='img-item' key={f.id}>
          {
            f.url===''?<Icon type='loading'></Icon>:
            <div>
              <img src={BASEURL+f.url} alt="" onClick={()=>{}}/>
              <Icon className='img-del-btn' type='cross-circle-o' color='#21b97a' onClick={()=>deletedImg(index)}></Icon>
              {
                f.status==='error'?<i className='iconfont icon-report' ></i>
                :null
              }
              
            </div>
          }
        </div>
        ))
      }
      {
        (limit!==undefined&&fileData.length<limit)||(limit===undefined&&fileData.length<initLimit)?
        <form className='img-item add' id='uploader'>
          <input type="file" accept='image/*' onChange={inputChange}/>
          <i className='iconfont icon-add'></i>
        </form>:
        null
      }
      
    </div>
  )
}
